package com.javastudy;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
//import java.util.Base64;

public class MyClassLoader extends ClassLoader{

    public static void main(String[] args) {
        try{
            Class<?> clazz = new MyClassLoader().findClass("Hello").newInstance().getClass();
            Method m1 = clazz.getDeclaredMethod("hello");
            m1.invoke(clazz.newInstance());
            //new MyClassLoader().findClass("Hello").newInstance();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch(InstantiationException | NoSuchMethodException e){
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = decode(getFileBytes("src/Hello.xlass"));

        return defineClass(name, bytes, 0, bytes.length);
    }

    //解码为jvm能够识别的字节码
    public byte[] decode(byte[] x){
        byte[] dataTemp = new byte[x.length];

        for(int i = 0; i < x.length; i++){
            dataTemp[i] = (byte)(255 - x[i]);
            //System.out.println(dataTemp[i]);
        }

        return dataTemp;
    }

    //读取文件到byte[]
    public byte[] getFileBytes(String x) {
        try {
            File file = new File(x);
            int length = (int) file.length();
            byte[] data = new byte[length];
            new FileInputStream(file).read(data);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
